package com.fh.resolver;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.fh.util.R;
/**
 * 
* 类名称：MyExceptionResolver.java
* 类描述： 
* @author fuhang
* 作者单位： 
* 联系方式：
* @version 1.0
 */
public class MyExceptionResolver implements HandlerExceptionResolver{

	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		// TODO Auto-generated method stub
		String url = request.getServletPath();
		if(url.startsWith("/api")){//api返回异常拦截
			try {
				JSONObject j = JSONObject.fromObject(R.error("服务器异常！请联系管理员"));
				response.setContentType("application/json"); 
				response.setCharacterEncoding("utf-8");
				response.getWriter().print(j.toString());
				return null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		System.out.println("==============异常开始=============");
		ex.printStackTrace();
		System.out.println("==============异常结束=============");
		ModelAndView mv = new ModelAndView("error");
		mv.addObject("exception", ex.toString().replaceAll("\n", "<br/>"));
		return mv;
	}

}
